#include "StdAfx.h"
#include "WavePlayer.h"
#include "math.h"

#define MAGIC_NUMBER 1.05946309

CWavePlayer::CWavePlayer(void)
{
	mSamples = NULL;
	mNumSamples = 0;
	mSpeed = 1.;
}


CWavePlayer::~CWavePlayer(void)
{
}

void CWavePlayer::Start( void )
{
	mPosition = 0.;
}

bool CWavePlayer::Generate( void )
{
	if( (int)mPosition < mNumSamples  && (int)(mPosition+1) < mNumSamples)
	{
		//Interpolate between the two pitches.
		double lLowerGain = fmod(mPosition, 1.0);
		int lLower = (int)(mPosition - lLowerGain);

		mFrame[0] = (mSamples[lLower] * lLowerGain/ 32768.0) + (mSamples[lLower++] * (1 - lLowerGain) / 32768.0 );
		mFrame[1] = mFrame[0];

		mPosition += mSpeed;

		return true;
	}
	else
	{
		mFrame[1] = mFrame[0] = 0;
		return false;
	}
}

void CWavePlayer::SetPlaybackSpeed( double aNumHalfSteps )
{
	if ( aNumHalfSteps > 0 )
		mSpeed = pow( MAGIC_NUMBER , aNumHalfSteps );
	else if ( aNumHalfSteps < 0 )
		mSpeed = pow( MAGIC_NUMBER , 1/abs(aNumHalfSteps) );
	else
		mSpeed = 1.0;
}